//
//  FMCommentViewController.m
//  PsychologyFM
//
//  Created by zhang on 16/1/13.
//  Copyright © 2016年 ZhangLuDu. All rights reserved.
//

#import <FMDB.h>
#import "FMPersonViewController.h"
#import "FMEditCommentViewController.h"
#import "FMRootViewController.h"
#import "FMDetailsCellHeaderView.h"
#import "FMCommentTableViewCell.h"
#import "FMCommentModel.h"
#import "FMCommentViewController.h"
#import "MJRefresh.h"
#import "FMLoginViewController.h"


@interface FMCommentViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,commentDelegate>
@property (nonatomic, strong) FMDetailsCellHeaderView *headerView;
//添加自定义nageviTionBar
@property (nonatomic, strong) UIView *nagevitionBarView;

//创建回复的view 能够弹出和消失
@property (nonatomic, strong) UIImageView *repeatView;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, strong) UITapGestureRecognizer *tap;

//添加一个状态 判断是否显示repeatView
@property (nonatomic, assign) BOOL isRepeatOn;

//添加登陆状态
@property (nonatomic, strong) NSString *islogin;
//设备的token值
@property (nonatomic, strong) NSString *token;

@end

@implementation FMCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isRepeatOn = NO;
    
    [self addUITapgestureRecogrnize];
    self.view.backgroundColor = FMWhite;
    [self addNageVitionBar];
    [self getInformation];
    [self addTableView];
    self.offset = 0;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.offset += 10;
        [self getInformation];
        
    }];
    
}
#pragma mark 添加轻拍手势
- (void)addUITapgestureRecogrnize{

    self.tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    _tap.delegate = self;
//    [self.view addGestureRecognizer:_tap];
    
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    
    NSIndexPath *path = [NSIndexPath indexPathForRow:self.num - 10 inSection:0];
    FMCommentTableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
    
    NSInteger index = self.num - 10;
    
    NSLog(@"%ld",(long)index);
    
    FMCommentModel *model = self.commontArray[index];
    

    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UIImageView"]) {
        
      CGPoint point =   [touch locationInView:self.view];
        NSLog(@"%@",[NSValue valueWithCGPoint:point]);
        if (point.x < 275) {
            NSLog(@"回复");
            NSLog(@"%@",model.floor);
  
        }else{
            NSLog(@"举报你了哦");
            [self report];
        }
        
    }else{
        cell.repeatView.hidden = YES;
    }
    [self.view removeGestureRecognizer:_tap];

    
    return YES;
    
}
// 实现举报功能
- (void)report{

    self.reportLable = [[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth - 150) / 2,100 , 150, 60)];
    self.reportLable.text = @"举报成功";
    self.reportLable.layer.cornerRadius = 5;
    _reportLable.layer.masksToBounds = YES;
    self.reportLable.textAlignment = NSTextAlignmentCenter;
    self.reportLable.backgroundColor  = FMGray;
    [self.view addSubview:_reportLable];
    
    [self performSelector:@selector(reportL) withObject:nil afterDelay:2];

}

- (void)reportL{

    [self.reportLable removeFromSuperview];
}
- (void)tapAction{

  //  NSLog(@"123");
}


#pragma mark 添加nagevitonBar
- (void)addNageVitionBar{
    self.nagevitionBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
//    添加返回按钮
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(20, 10, 30, 30);
    [backButton setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [backButton addTarget:self action:@selector(backButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.nagevitionBarView addSubview:backButton];
    [self.view addSubview:_nagevitionBarView];
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth - 40) / 2, 0, 40, 40)];
    titleLable.text = @"详情";
    [self.nagevitionBarView addSubview:titleLable];
    
    
}
- (void)backButton:(UIButton *)backButton{

    [self.navigationController popToRootViewControllerAnimated:YES];

}
#pragma mark 添加tableView
- (void)addTableView{

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,64, kScreenWidth, kScreenHeight - 60) style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    设置tableViewde总表头
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName ,nil];
    
    CGRect frame = [self.cellModel.content boundingRectWithSize:CGSizeMake(kScreenWidth - 20,CGFLOAT_MAX ) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    

    
    self.headerView = [[FMDetailsCellHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, (kScreenWidth/8 + kMartin10 + frame.size.height + kMartin10 + (self.cellModel.images.count )* (((kScreenWidth - kMartin20) / 540 * 960 ) - 30)))];
    _headerView.model = self.cellModel;
    self.tableView.tableHeaderView = _headerView;
    [self.tableView registerClass:[FMCommentTableViewCell class] forCellReuseIdentifier:@"MyCell"];
    [self.view addSubview:_tableView];
    

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

   return  self.commontArray.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    FMCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
    FMCommentModel *model = self.commontArray[indexPath.row];
    cell.model = model;
    
    cell.repeatButton.tag = indexPath.row + 10;
    [cell.repeatButton addTarget:self action:@selector(repeatButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.avatarButton addTarget:self action:@selector(avatarButton:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.avatarButton.tag = [model.user_id intValue] ;
    return cell;


}
//实现cell的repeatButton的方法
- (void)repeatButton:(UIButton *)repeatButton{
    NSIndexPath *path = [NSIndexPath indexPathForRow:repeatButton.tag - 10 inSection:0];
    FMCommentTableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
    
    self.num = repeatButton.tag;

    if (self.isRepeatOn == NO) {
        cell.repeatView.hidden = NO;
        self.isRepeatOn = YES;
    }else{
        cell.repeatView.hidden = YES;
        self.isRepeatOn = NO;
        
    }
        [self.view addGestureRecognizer:_tap];


}

//点击头像跳转到个人主页
- (void)avatarButton:(UIButton *)button{

    FMPersonViewController *personVC = [[FMPersonViewController alloc]init];
    
  

    personVC.user_id = [NSString stringWithFormat:@"%ld",(long)button.tag];
    
    [self.navigationController pushViewController:personVC animated:YES];
    
}


// 根据触摸判断 隐藏repeatView
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //判断点击的范围是不是在 repeatView的范围内 如果不在 就移除
    
//    UITouch 保存了你触摸的信息 例如触摸的点
  //  UITouch *touoch =  [touches anyObject];
//    取出当前触摸的点
  //  CGPoint Ptouch = [touoch locationInView:self.tableView];
   
 //   NSIndexPath *path = [NSIndexPath indexPathForRow:self.num - 10 inSection:0];
 //   FMCommentTableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
    
    
//    if (CGRectContainsPoint(self.tableView.frame, Ptouch) ) {
//        NSLog(@"caimoma");
//    }else{
//        NSLog(@"nimabi");
//    }

}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//    NSLog(@"1111");
}


#pragma mark 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FMCommentModel *model = self.commontArray[indexPath.row];
    
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName ,nil];
    
    CGRect frame = [model.content boundingRectWithSize:CGSizeMake(kScreenWidth - kScreenWidth / 10 - kMartin25,CGFLOAT_MAX ) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    
    return kMartin10 + kScreenWidth/10 + frame.size.height + kMartin15  + kMartin15 + kMartin15;

}

#pragma mark 返回表头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    //NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName ,nil];
//    
//    CGRect frame = [self.cellModel.content boundingRectWithSize:CGSizeMake(kScreenWidth - 20,CGFLOAT_MAX ) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
////    NSLog(@"%f",frame.size.height);
//// 有图片时  图片的高度
//    CGFloat imageHeight = (kScreenWidth - kMartin20) / 540 * 960 ;
////    NSLog(@"-----%f",imageHeight);
//   // CGFloat height =(imageHeight + kMartin10);
    
    return kMartin10 + kScreenWidth/8 + kMartin10 + kMartin25 + kMartin15 + kMartin15 + kMartin10 ;
}

#pragma mark 进行网络请求
- (void)getInformation{

   // http://yiapi.xinli001.com/fm/forum-comment-list.json?post_id=6273&key=c0d28ec0954084b4426223366293d190&offset=0&limit=10

    NSString *str = @"http://yiapi.xinli001.com/fm/forum-comment-list.json?";

    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
   parDic[@"post_id"] = [NSString stringWithFormat:@"%@",self.cellModel.ID];

    parDic[@"key"] = @"c0d28ec0954084b4426223366293d190";
    parDic[@"offset"] = [NSString stringWithFormat:@"%lud",(long)self.offset];
    parDic[@"limit"] = @"10";
    
//    get请求 进行字符串拼接
//    1. 先把字典的键值对以一定格式存储在数组里面
    // 初始化一个字典用来后面保存格式化的字符串键值对
    NSMutableArray *strArray = [NSMutableArray array];
    // 遍历字典
    for (NSString *key in parDic) {
        // 以key=value形式存储键值对于数组中
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
        [strArray addObject:str];
    }
//    2.将数组里面的元素 组成字符串
    NSString *arrayStr = [strArray componentsJoinedByString:@"&"];
//    3.合成最后需要的网址
    NSString *urlStr = [str stringByAppendingString:arrayStr];
//    NSLog(@"%@",urlStr);

    
    [PKRequestManager requestWithUrlString:urlStr parDic:parDic method:GET finish:^(NSData *data) {
       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] ;
        NSDictionary *dicPost = dic[@"post"];
        [_cellModel setValuesForKeysWithDictionary:dicPost];
        
        //存储评论的人
        if (self.commontArray == nil) {
            self.commontArray = [NSMutableArray array];

        }
        
        NSArray *dataArray = dic[@"data"];
        for (NSDictionary *dicOne in dataArray) {
            FMCommentModel *model = [[FMCommentModel alloc]init];
            [model setValuesForKeysWithDictionary:dicOne];
            [self.commontArray addObject:model];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];

    } error:^(NSError *error) {
        
        ;
    }];
    
    
}

#pragma mark 添加评论和分享
- (void)addShareView{

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.shareView = [[UIImageView alloc]initWithFrame:CGRectMake(0, kScreenHeight - 49 , kScreenWidth, 49)];
    self.shareView.userInteractionEnabled = YES;
    self.shareView.backgroundColor = [UIColor colorWithRed:36/255.0 green:39/255.0 blue:42/255.0 alpha:1];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(kScreenWidth / 2, 15, 2, 20)];
    view.backgroundColor = FMWhite;
    [self.shareView addSubview:view];
    //评论图片
    UIButton *commentButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    commentButton.frame = CGRectMake(kScreenWidth / 2 - kScreenWidth/ 3, 5, kScreenWidth/8, 49) ;
    [commentButton setImage:[UIImage imageNamed:@"comment1@2x"] forState:(UIControlStateNormal)];
    [commentButton addTarget:self action:@selector(comment:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.shareView addSubview:commentButton];
    //评论按钮
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(commentButton.right, 0, kScreenWidth/8, 49);
    [button setTitle:@"评论" forState:(UIControlStateNormal)];
    [button setTitleColor:FMWhite forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(comment:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.shareView addSubview:button];
    //分享图片
    UIButton *shareImage = [UIButton buttonWithType:(UIButtonTypeCustom)];
    shareImage.frame =    CGRectMake(kScreenWidth / 2 + kScreenWidth/ 9, 7, kScreenWidth/12, kScreenWidth/12);
    [shareImage setImage:[UIImage imageNamed:@"tieziShare@2x"] forState:(UIControlStateNormal)];
    [shareImage addTarget:self action:@selector(share:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.shareView addSubview:shareImage];
    //分享按钮

    UIButton *sharebutton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    sharebutton.frame = CGRectMake(shareImage.right + kMartin10, 0, kScreenWidth/8, 49);
    [sharebutton setTitle:@"分享" forState:(UIControlStateNormal)];
    [sharebutton addTarget:self action:@selector(share:) forControlEvents:(UIControlEventTouchUpInside)];
    [sharebutton setTitleColor:FMWhite forState:(UIControlStateNormal)];
    [self.shareView addSubview:sharebutton];
    
    
    [self.rootVC.view addSubview:self.shareView];


}
//评论的方法
- (void)comment:(UIButton *)button{

        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"FMDataBase.db"];
    
    FMDatabase  *db = [FMDatabase databaseWithPath:path];
    
    [db open];
    
    FMResultSet *result =  [db executeQuery:@"SELECT isLogin,token FROM UserInformationlist"];

    
    
    while ([result next]) {
//        获取登陆状态
        _islogin = [result stringForColumn:@"isLogin"];
//        获取设备的token值
        _token = [result stringForColumn:@"token"];
    }
    
        if ([_islogin isEqualToString:@"YES"] ) {
            FMEditCommentViewController *editVC = [[FMEditCommentViewController alloc]init];
            
//            准备拼接提交网址
            editVC.reply_user_id = self.cellModel.user_id;
            editVC.token = self.token;
            editVC.post_id = self.cellModel.ID;
            editVC.commVC = self;
            editVC.delegate = self;
            
            [self presentViewController:editVC animated:YES completion:nil];
        } else {

            FMLoginViewController *fmLoginVC = [[FMLoginViewController alloc]init];
            [self.navigationController pushViewController:fmLoginVC animated:YES];
  
    
        }

    

}
#pragma mark -- 提交评论


//实现代理的方法 刷新界面
- (void)passData:(NSData *)data{

    [self.commontArray removeAllObjects];
    [self getInformation];
    
}

//分享的方法
- (void)share:(UIButton *)button{

}
- (void)loadView{
 
    [super loadView];
}
- (void)viewWillAppear:(BOOL)animated{
    
   [self addShareView];
    self.rootVC.tabbar.hidden = YES;
//    self.rootVC.scrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight  );
    self.rootVC.scrollView.scrollEnabled = NO;
    
    
}
- (void)viewWillDisappear:(BOOL)animated{

    UITabBar *tab = (UITabBar *)[self.navigationController.view.superview.superview viewWithTag:6];
    tab.hidden = NO;
    [self.shareView removeFromSuperview];
    self.rootVC.scrollView.scrollEnabled = YES;
    //self.rootVC.scrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49 );


}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
